import { InfiniteScroll, Input, Toast } from 'antd-mobile'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Parser, Player } from 'svga'
import { useNavigate } from 'react-router-dom'
import { GetUserInfo, getMutualAttentionUsers, getUserinfoById } from '../../api/mine'
import { GetMallList, GetShopType, ShopBuy, ShopSend } from '../../api/shop'
import NavBar from '../../components/Navbar'
import AmePopup from '../../components/Popup'
import './index.less'
// import GiftShow from "../../components/GiftShow";
import { loadZipAnimation } from '../../utils/util'
import AmeModal from '../../components/AmeModal'
// import Lottie from "lottie-web";
// import data from "../../lottie/data1.json"
// import { loadZipAnimation } from "../../utils/util";

// 1:贵族解锁 2:活动所得 6:限时购买 8:cp解锁 10:签到所得 14:积分商城 17:财富解锁  18:魅力解锁
const typeValue = {
  1: '贵族解锁',
  2: '活动所得',
  6: '限时购买',
  8: 'cp解锁',
  10: '签到所得',
  14: '积分商城',
  17: '财富解锁',
  18: '魅力解锁',
  30: '首充奖励'
}
let selectUser = null
export default function Products() {
  const navigate = useNavigate()
  const [menu, setMenu] = useState([])
  const [activeMenu, setActiveMenu] = useState('')
  const [data, setData] = useState([])
  const [selectItem, setSelectItem] = useState()
  const [userInfo, setUserInfo] = useState({ mizuan: 0 })
  const [paySelect, setPaySelect] = useState({ price: 0 })

  const [userListVisible, setUserListVisible] = useState(false)
  const [searchUserData, setSearchUser] = useState([])

  const svgaPlay = useRef()
  const inputRef = useRef()

  const getType = () => {
    GetShopType().then((res) => {
      setMenu(res?.data)
      setActiveMenu(res?.data[0].id)
    })
  }

  const getInfo = () => {
    GetUserInfo().then((res) => {
      setUserInfo(res.data)
    })
  }

  const getProducts = () => {
    GetMallList({ type: activeMenu }).then((res) => {
      console.log(res)
      if (res.data) {
        setData(res?.data || [])
      } else {
        setData([])
      }
    })
  }

  useEffect(() => {
    getType()
    getInfo()

    // loadZipAnimation('https://upic-1252665534.cos.ap-guangzhou.myqcloud.com/uPic/lottie/lot.zip')

    // getZipFiles().then((res) => {
    //   console.log(res);
    //   res['data.json'].async('blob').then((data) => {
    //     console.log(data);
    //     Lottie.loadAnimation({
    //       container: document.getElementById('lottie'), // the dom element that will contain the animation
    //       renderer: 'svg',
    //       loop: true,
    //       autoplay: true,
    //       animationData: JSON.parse(data)
    //       // path: data.text()
    //     });
    //   })
    // })
  }, [])

  const [visible, setVisible] = useState(false)
  const openPop = (item) => {
    if (item.type === 10 && item.is_buy === 0) return false
    if (item.get_type in typeValue) return false
    if (item.sku) {
      setSelectItem(item)
    } else {
      item.sku = [
        {
          id: item.id,
          name: item.name,
          price: item?.price,
          expire: item?.expires,
          give_point: item?.give_points
        }
      ]
      setSelectItem(item)
    }
    playGift(item.img3 || item.img2)
    setPaySelect(item?.sku[0])
    setVisible(true)
  }

  const [playType, setPlayType] = useState(0) // 0 img 1 lotter 2 svga
  const playGift = (url) => {
    if (!url) {
      setPlayType(0)
      return false
    }
    if (url.includes('zip')) {
      setPlayType(1)
      loadZipAnimation(url, 'gift_show')
    }
    if (url.includes('svga')) {
      setPlayType(2)
      playSvga(url, 'gift_show')
    }
  }

  const playSvga = async (url) => {
    Toast.show({ icon: 'loading' })
    const parser = new Parser()
    const svga = await parser.load(url)

    const player = new Player(document.getElementById('gift_show'))
    await player.mount(svga)
    svgaPlay.current = player
    Toast.clear()
    player.start()
  }

  const AmePopupClose = () => {
    setVisible(false)
    setSelectItem(null)
    setPlayType(null)
    if (svgaPlay.current) {
      svgaPlay.current.destroy()
      svgaPlay.current = null
    }
  }

  const [hasMore, setHasMore] = useState(true)
  const [page, setPage] = useState(1)

  const requestUserList = async () => {
    return getMutualAttentionUsers({
      page: page,
      keyword: inputRef.current.nativeElement?.value || undefined
    })
      .then((res) => {
        console.log('requestUserList', res)
        if (res.data && res.data?.length) {
          setSearchUser(searchUserData.concat(res.data))
        }
        if (res.data && res.data?.length >= 10) {
          setPage(page + 1)
          setHasMore(true)
        } else {
          setHasMore(false)
        }
      })
      .catch(() => {
        setHasMore(false)
      })
  }

  const buyThing = (type) => {
    if (type === 'buy') {
      if (Number(userInfo.mizuan) >= Number(paySelect.price)) {
        Toast.show({ content: 'loading...', maskClickable: false, icon: 'loading', duration: 6000 })
        ShopBuy({ goods_id: paySelect?.id })
          .then((res) => {
            console.log(res)
            Toast.show({ content: '购买成功', maskClickable: false, icon: 'success' })
            // setVisible(false)
            // setSelectItem(null);
            AmePopupClose()
          })
          .finally(() => {
            // Toast.clear()
            getInfo()
            getProducts()
          })
      } else {
        setModalText(`${window.baseConfig.coin_name}余额不足请充值`)
      }
    } else {
      // requestUserList();
      // getMutualAttentionUsers({
      //   page: 1
      // }).then(res => {
      //   console.log('关系近的数据', res.data);
      //   setSearchUser(res?.data || [])
      // }).finally(() => {
      setHasMore(true)
      setPage(1)
      setUserListVisible(true)
      // })
    }
  }

  useEffect(() => {
    if (activeMenu) {
      getProducts()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeMenu])

  const searchUser = () => {
    if (inputRef.current.nativeElement?.value) {
      setPage(1)
      setHasMore(true)
      setSearchUser([])
      getMutualAttentionUsers({
        page: 1,
        keyword: inputRef.current.nativeElement?.value
      }).then((res) => {
        console.log(res)
        setSearchUser(res?.data)
      })
    } else {
      Toast.show({ content: '请输入你要赠送的用户ID' })
    }
  }

  const [modalText, setModalText] = useState('')
  const sendGift = (type) => {
    console.log(paySelect, type)
    if (type === 'send') {
      Toast.show({ icon: 'loading', maskClickable: false })
      ShopSend({
        goods_id: paySelect?.id,
        give_id: selectUser?.id
      })
        .then((res) => {
          Toast.show({ content: '赠送成功～', maskClickable: false, icon: 'success' })
          setUserListVisible(false)
          setSearchUser([])
          setModalText(undefined)
        })
        .finally(() => {
          getInfo()
        })
    } else {
      selectUser = type // 这时候的type 是id
      if (Number(userInfo.mizuan) >= Number(paySelect.price)) {
        setModalText(`是否赠送“${paySelect.name}/${Number(paySelect?.expire) ? `${paySelect?.expire}天` : '永久'}”给 ${type.nickname}`) // /${paySelect?.expires || paySelect?.expire}天
      } else {
        setModalText(`${window.baseConfig.coin_name}余额不足请充值`)
      }
    }
  }

  return (
    <div className="mall">
      <NavBar title="商城" />
      <div className="menu_list">
        {menu.map((i) => (
          <div key={i.id} className={`text ${activeMenu === i.id ? 'active' : ''}`} onClick={() => setActiveMenu(i.id)}>
            {i.name}
          </div>
        ))}
      </div>
      <div className="scroll">
        <div className="content">
          {data.map((item) => (
            <div className={`item ${selectItem?.id === item.id ? 'active' : ''}`} key={item.id} onClick={() => openPop(item)}>
              {item.get_type in typeValue ? (
                <div className="tag">
                  <span>{typeValue[item.get_type]}</span>
                </div>
              ) : null}
              <div className="item_img">
                {item.type === 10 ? (
                  <div className={`special_number ${item.is_buy === 0 ? 'disabled' : ''}`}>
                    {item.name.split('').map((t) => (
                      <span className={`n n-${t}`}></span>
                    ))}
                  </div>
                ) : (
                  <img src={item.show_img} alt="" />
                )}
              </div>
              {item.type === 10 && item.is_buy === 0 ? <div className="sale_down"></div> : null}
              <div className="item_tit ellipsis1">{item.name}</div>
              <div className="price">
                <span>{item.price}</span>
                <div className="unit_icon"></div>
                {item.expires ? (
                  <span>
                    {+item.expires?.split(',')[0] ? `/${item.expires?.split(',')[0] > 1 ? item.expires?.split(',')[0] : ''}天` : '永久'}
                  </span>
                ) : null}
              </div>
            </div>
          ))}
        </div>
      </div>
      {/* <div id="lottie" style={{ width: 200, height: 200 }}></div> */}

      <AmePopup visible={visible} AmePopupClose={AmePopupClose}>
        <div className="sku_content">
          {selectItem?.type === 10 ? (
            <div className="special_number_show">
              <div className="user_card">
                <div className="avatar">
                  <img src={userInfo.headimgurl} alt="" />
                </div>
                <div className="info">
                  <div className="special_name">{userInfo.nickname}</div>
                  <div className="special_number_s">
                    <span className="icon"></span>
                    ID: {selectItem.name}
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="image">
              {+paySelect?.give_point ? <span className="give_tag">+{paySelect?.give_point}积分</span> : null}
              {/* <img src={selectItem.show_img} alt="" /> */}
              {playType === 0 ? <img src={selectItem?.show_img} alt="" /> : null}
              {playType === 1 ? <div id="gift_show"></div> : null}
              {playType === 2 ? <canvas id="gift_show"></canvas> : null}
            </div>
          )}

          <div className="name">{selectItem?.name}</div>
          <div className={`sku_items ${selectItem?.sku?.length === 1 ? 'simple' : ''}`}>
            {selectItem?.sku.map((item) => (
              <div onClick={() => setPaySelect(item)} className={`sku_item ${item.id === paySelect.id ? 'active' : ''}`} key={item.id}>
                <p className="expire">{`${+item.expire ? item.expire + '天' : '永久'}`}</p>
                <p className="price">
                  {item.price}
                  {window.baseConfig.coin_name}
                </p>
              </div>
            ))}
          </div>
          <div className="pay_wrap">
            <div className="my_wallet">
              <div className="icon"></div>
              <div className="num">{+userInfo?.mizuan || 0}</div>
              <div className="recharge" onClick={() => navigate('/recharge')}>
                <span>充值</span> &gt;
              </div>
            </div>
            <div className="pay_btn send" onClick={() => buyThing('send')}>
              <div className="icon" />
              赠送
            </div>
            <div className="pay_btn" onClick={() => buyThing('buy')}>
              立刻购买
            </div>
          </div>
        </div>
      </AmePopup>
      <AmePopup
        visible={userListVisible}
        AmePopupClose={() => {
          setUserListVisible(false)
          setSearchUser([])
          setHasMore(true)
        }}
      >
        {userListVisible ? (
          <div className="send_content">
            <div className="tit">礼物赠送</div>
            <div className="content_c">
              <div className="search_wrap">
                <div className="search_icon"></div>
                <Input ref={inputRef} placeholder="请输入用户ID" maxLength={20} />
                <div className="search_btn" onClick={searchUser}>
                  搜索
                </div>
              </div>
              <div className="list">
                {searchUserData?.map((item) => (
                  <div className="item">
                    <div className="user_info">
                      <div className="avatar">
                        <img src={item.headimgurl} alt="" />
                      </div>
                      <div className="info">
                        <div className="name">{item.nickname}</div>
                        <div className="user_id">ID：{item.id}</div>
                      </div>
                    </div>
                    <div className="send_btn" onClick={() => sendGift(item)}>
                      赠送
                    </div>
                  </div>
                ))}
                <InfiniteScroll loadMore={requestUserList} hasMore={hasMore} />
              </div>
            </div>
          </div>
        ) : null}
      </AmePopup>

      <AmeModal
        visible={Boolean(modalText)}
        title={modalText}
        onCancel={() => setModalText(undefined)}
        onConfirm={() => {
          if (Number(userInfo.mizuan) >= Number(paySelect?.price)) {
            sendGift('send')
          } else {
            navigate('/recharge')
          }
        }}
        confirmText={Number(userInfo.mizuan) >= Number(paySelect?.price) ? '确认' : '去充值'}
      ></AmeModal>
    </div>
  )
}
